/**
 * 
 */
package com.tomato.joke.persistence.dao.base;

import java.sql.SQLException;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import com.tomato.joke.utils.ReflectionUtils;

/**
 * DAO支持类
 * @author defier
 *
 */
public class OrmLiteDaoSupport<T, PK> extends OrmLiteSqliteOpenHelper {

	 private static final String DATABASE_NAME = "tomato_joke.db";  
	 private static final int DATABASE_VERSION = 1;
	 
	 protected Class<T> entityClass;
	 private Dao<T, PK> dao = null;
	    
	public OrmLiteDaoSupport(Context context){  
        super(context, DATABASE_NAME, null, DATABASE_VERSION); 
        this.entityClass = ReflectionUtils.getSuperClassGenricType(getClass());
    }
	
	
	@Override
	public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
		try {
			Log.i(OrmLiteDaoSupport.class.getName(), "onCreate");
			TableUtils.createTable(connectionSource, entityClass);
			Dao<T, PK> dao = getDao();
			long millis = System.currentTimeMillis();
			dao.create(entityClass.newInstance());
			Log.i(OrmLiteDaoSupport.class.getName(), "created new entries in onCreate: " + millis);
		} catch (Exception e) {
			Log.e(OrmLiteDaoSupport.class.getName(), "Can't create database", e);
			throw new RuntimeException(e);
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {
		try {
			Log.i(OrmLiteDaoSupport.class.getName(), "onUpgrade");
			TableUtils.dropTable(connectionSource, entityClass, true);
			onCreate(db, connectionSource);
		} catch (Exception e) {
			Log.e(OrmLiteDaoSupport.class.getName(), "Can't drop databases", e);
			throw new RuntimeException(e);
		}
	}

	public Dao<T, PK> getDao() throws SQLException {
		if (dao == null) {
			dao = getDao(entityClass);
		}
		return dao;
	}

	@Override
	public void close() {
		super.close();
		dao = null;
	}

}
